package com.example.ywj.toutiao;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.login_back)
    public TextView login_back;
    @BindView(R.id.login_next)
    public TextView login_next;
    @BindView(R.id.login_phone)
    public EditText login_phone;
    @BindView(R.id.register)
    public TextView register;
    private String baseUrl = Constant.BASEURL;
    Boolean flag = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //overridePendingTransition(0, 0);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//因为不是所有的系统都可以设置颜色的，在4.4以下就不可以。。有的说4.1，所以在设置的时候要检查一下系统版本是否是4.1以上
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.trgray));
        }
        initView();
        login_phone.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                  Boolean b = testPhone(String.valueOf(s));

                if(b) {
                    getUsername(String.valueOf(s));
                }else{
                    login_next.setBackground(getResources().getDrawable(R.drawable.border_textview));
                    //login_next.setTextColor(getColor(R.color.white));
                }
                Log.i(TAG, "onTextChanged: "+s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }
    public void getUsername(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getUsername(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    login_next.setBackground(getResources().getDrawable(R.drawable.border_textview2));
                    login_next.setTextColor(getColor(R.color.white));
                    flag = true;
                }else{
                    Toasty.error(LoginActivity.this, "您还未注册", Toast.LENGTH_SHORT, true).show();
                    flag = false;
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }
    public void initView(){
        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        login_back.setTypeface(font);
        login_back.setText(getResources().getString(R.string.cha));
        login_next.setTypeface(font);
        login_next.setText(getResources().getString(R.string.next));
        login_back.setOnClickListener(this);
        login_next.setOnClickListener(this);
        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login_back:
                finish();
                break;
            case R.id.login_next:
                Boolean b = testPhone(login_phone.getText().toString());
                if(b && flag){
                    Bundle bundle = new Bundle();
                    bundle.putString("username",login_phone.getText().toString());
                    Intent intent = new Intent(LoginActivity.this,PasswordActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                    overridePendingTransition(0, 0);
                }else{
                    Toasty.error(LoginActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT, true).show();
                    login_phone.setText("");
                }
                break;
            case R.id.register:
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }
    public Boolean testPhone(String account) {
        Pattern p = Pattern.compile("^1[0-9]{10}$");
        Matcher m = p.matcher(account);
        boolean b = m.matches();
        return b;

    }

    @Override
    protected void onPause() {
        overridePendingTransition(0, 0);
        super.onPause();
    }
}
